﻿namespace UnityEditor.Graphs
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using UnityEditor;
    using UnityEditor.Graphs.AnimationBlendTree;
    using UnityEditor.Graphs.AnimationStateMachine;
    using UnityEditorInternal;
    using UnityEngine;

    internal class AnimatorControllerTool : EditorWindow
    {
        [SerializeField]
        public UnityEditor.Graphs.AnimationBlendTree.Graph blendTreeGraph;
        [SerializeField]
        public UnityEditor.Graphs.AnimationBlendTree.GraphGUI blendTreeGraphGUI;
        public static System.Action graphDirtyCallback;
        private const float kAdditionalLayerContentsHeight = 81f;
        private const float kBaseLayerContentsHeight = 43f;
        private const float kBottombarHeight = 24f;
        private const float kCollapsedLayerHeight = 23f;
        private const float kEventElementHeight = 20f;
        private const float kEventHeaderHeight = 26f;
        private const float kEventValueWidth = 31f;
        private const float kEventVectorValueWidth = 92f;
        private const float kLayerHeaderHeight = 30f;
        private const float kSidebarWidth = 220f;
        private const float kToolbarHeight = 17f;
        [SerializeField]
        private AnimatorController m_AnimatorController;
        [SerializeField]
        private bool m_AutoLiveLink = true;
        [SerializeField]
        private List<BreadCrumbElement> m_BreadCrumbs;
        private Vector2 m_EventScroll;
        private List<bool> m_LayerExpansion;
        private Vector2 m_LayerScroll;
        [SerializeField]
        private Animator m_PreviewObject;
        [SerializeField]
        private int m_SelectedLayerIndex;
        private static Styles s_Styles;
        [SerializeField]
        public UnityEditor.Graphs.AnimationStateMachine.Graph stateMachineGraph;
        [SerializeField]
        public UnityEditor.Graphs.AnimationStateMachine.GraphGUI stateMachineGraphGUI;
        public static AnimatorControllerTool tool;

        public AnimatorControllerTool()
        {
            tool = this;
        }

        public void AddBreadCrumb(UnityEngine.Object target)
        {
            this.m_BreadCrumbs.Add(new BreadCrumbElement(target));
            this.stateMachineGraphGUI.CenterGraph();
            this.blendTreeGraphGUI.CenterGraph();
        }

        private void AddEventMenu(object value)
        {
            Undo.RegisterUndo(this.animatorController, "Parameter Added");
            AnimatorControllerEventType type = (AnimatorControllerEventType) ((int) value);
            this.animatorController.AddEvent(MakeUniqueParameterName("New " + type.ToString(), this.animatorController), type);
        }

        private bool BeginLayer(int layerIndex)
        {
            GUILayoutGroup group = GUILayoutUtility.BeginLayoutGroup(s_Styles.layerBox, null, typeof(GUILayoutGroup));
            group.isVertical = true;
            if (Event.current.type == EventType.Repaint)
            {
                s_Styles.layerBox.Draw(group.rect, GUIContent.Temp(this.animatorController.GetLayerName(layerIndex)), 0, this.m_SelectedLayerIndex == layerIndex);
            }
            GUILayout.BeginHorizontal(new GUILayoutOption[0]);
            bool flag = GUILayout.Toggle(this.m_LayerExpansion[layerIndex], GUIContent.none, s_Styles.layerFoldout, new GUILayoutOption[0]);
            GUILayoutOption[] options = new GUILayoutOption[] { GUILayout.ExpandWidth(true) };
            if (GUILayoutUtility.GetRect((float) 0f, (float) 20f, options).Contains(Event.current.mousePosition) && (Event.current.type == EventType.MouseDown))
            {
                bool flag2 = this.m_SelectedLayerIndex == layerIndex;
                this.m_SelectedLayerIndex = layerIndex;
                if (!flag2)
                {
                    this.ResetBreadCrumbs();
                }
                if (Event.current.clickCount == 2)
                {
                    flag = !this.m_LayerExpansion[layerIndex];
                }
                Event.current.Use();
            }
            if (flag != this.m_LayerExpansion[layerIndex])
            {
                this.m_LayerExpansion[layerIndex] = flag;
                this.ResetTextFields();
            }
            if ((this.animatorController.GetLayerCount() > 1) && (layerIndex > 0))
            {
                GUILayoutOption[] optionArray2 = new GUILayoutOption[] { GUILayout.Width(20f), GUILayout.Height(20f) };
                if (GUILayout.Button(s_Styles.removeIcon, s_Styles.invisbleButton, optionArray2))
                {
                    string title = "Delete layer " + this.animatorController.GetLayerName(layerIndex) + " ?";
                    string message = "You cannot undo this action.";
                    if (EditorUtility.DisplayDialog(title, message, "Delete", "Cancel"))
                    {
                        StateMachine layerStateMachine = this.animatorController.GetLayerStateMachine(layerIndex);
                        bool flag3 = ((this.animatorController.GetLayerSyncedIndex(layerIndex) == -1) && (layerStateMachine != null)) && MecanimUtilities.AreSameAsset(layerStateMachine, this.animatorController);
                        this.animatorController.RemoveLayer(layerIndex);
                        this.m_LayerExpansion.RemoveAt(layerIndex);
                        if (flag3)
                        {
                            MecanimUtilities.DestroyStateMachineRecursive(layerStateMachine);
                        }
                        if ((this.m_SelectedLayerIndex >= layerIndex) && (layerIndex != 0))
                        {
                            this.m_SelectedLayerIndex--;
                        }
                        this.ResetBreadCrumbs();
                        this.ResetTextFields();
                        Event.current.Use();
                        GUIUtility.ExitGUI();
                    }
                }
            }
            GUILayout.EndHorizontal();
            return this.m_LayerExpansion[layerIndex];
        }

        public void BlendTreeHierarchyChanged(BlendTree blendTree)
        {
            this.blendTreeGraph.BuildFromBlendTree(this.blendTreeGraph.rootBlendTree);
        }

        private void BlendTreeView(Rect position)
        {
            this.blendTreeGraph.previewAvatar = this.m_PreviewObject;
            this.blendTreeGraph.rootBlendTree = this.m_BreadCrumbs.Last<BreadCrumbElement>().target as BlendTree;
            this.blendTreeGraphGUI.BeginGraphGUI(this, position);
            this.blendTreeGraphGUI.OnGraphGUI();
            this.blendTreeGraphGUI.EndGraphGUI();
        }

        public void BuildBreadCrumbsFromSMHierarchy(IEnumerable<StateMachine> hierarchy)
        {
            this.m_BreadCrumbs.Clear();
            IEnumerator<StateMachine> enumerator = hierarchy.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    StateMachine current = enumerator.Current;
                    this.AddBreadCrumb(current);
                }
            }
            finally
            {
                if (enumerator == null)
                {
                }
                enumerator.Dispose();
            }
        }

        private void DetectAnimatorControllerFromSelection()
        {
            AnimatorController activeObject = null;
            if ((Selection.activeObject == null) && (this.animatorController == null))
            {
                this.animatorController = null;
            }
            if ((Selection.activeObject is AnimatorController) && EditorUtility.IsPersistent(Selection.activeObject))
            {
                activeObject = Selection.activeObject as AnimatorController;
            }
            if (Selection.activeGameObject != null)
            {
                Animator component = Selection.activeGameObject.GetComponent<Animator>();
                if (component != null)
                {
                    AnimatorController animatorController = AnimatorController.GetAnimatorController(component);
                    if (animatorController != null)
                    {
                        activeObject = animatorController;
                    }
                }
            }
            bool flag = false;
            if ((activeObject != null) && (activeObject != this.animatorController))
            {
                this.animatorController = activeObject;
                flag = true;
                if (this.animatorController == null)
                {
                    return;
                }
            }
            if (((this.m_LayerExpansion != null) && (this.animatorController != null)) && (flag || (this.m_LayerExpansion.Count != this.animatorController.GetLayerCount())))
            {
                this.m_LayerExpansion.Clear();
                for (int i = 0; i < this.animatorController.GetLayerCount(); i++)
                {
                    this.m_LayerExpansion.Add(false);
                }
            }
        }

        private void DetectPreviewObjectFromSelection()
        {
            if (Selection.activeGameObject != null)
            {
                Animator component = Selection.activeGameObject.GetComponent<Animator>();
                if ((component != null) && !AssetDatabase.Contains(Selection.activeGameObject))
                {
                    this.m_PreviewObject = component;
                }
            }
        }

        private void DoToolbar(Rect toolbarRect)
        {
            GUILayout.BeginArea(toolbarRect);
            GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]);
            BreadCrumbElement[] elementArray = this.m_BreadCrumbs.ToArray();
            for (int i = 0; i < elementArray.Length; i++)
            {
                BreadCrumbElement element = elementArray[i];
                EditorGUI.BeginChangeCheck();
                bool flag = GUILayout.Toggle(i == (elementArray.Length - 1), element.name, (i != 0) ? s_Styles.breadCrumbMid : s_Styles.breadCrumbLeft, new GUILayoutOption[0]);
                if (EditorGUI.EndChangeCheck() && flag)
                {
                    this.GoToBreadCrumbTarget(element.target);
                }
            }
            GUILayout.FlexibleSpace();
            if (Unsupported.IsDeveloperBuild() && GUILayout.Button("Select Graph", EditorStyles.toolbarButton, new GUILayoutOption[0]))
            {
                if (this.m_BreadCrumbs.Last<BreadCrumbElement>().target is StateMachine)
                {
                    Selection.activeObject = this.stateMachineGraph;
                }
                else
                {
                    Selection.activeObject = this.blendTreeGraph;
                }
            }
            BreadCrumbElement element2 = this.m_BreadCrumbs.LastOrDefault<BreadCrumbElement>();
            if ((element2 != null) && (element2.target is StateMachine))
            {
                this.m_AutoLiveLink = GUILayout.Toggle(this.m_AutoLiveLink, "Auto Live Link", EditorStyles.toolbarButton, new GUILayoutOption[0]);
            }
            GUILayout.EndHorizontal();
            GUILayout.EndArea();
        }

        [UnityEditor.MenuItem("Window/Animator", false, 0x7dc)]
        public static void DoWindow()
        {
            System.Type[] desiredDockNextTo = new System.Type[] { typeof(SceneView) };
            EditorWindow.GetWindow<AnimatorControllerTool>(desiredDockNextTo);
        }

        private void EndLayer()
        {
            GUILayoutUtility.EndLayoutGroup();
        }

        private void EventView(EditorWindow host, Rect position)
        {
            GUILayout.BeginArea(position, s_Styles.overlayArea);
            GUILayout.FlexibleSpace();
            if (!this.liveLink)
            {
                GUILayout.BeginHorizontal("Parameters", s_Styles.eventsHeader, new GUILayoutOption[0]);
            }
            else
            {
                GUILayout.BeginHorizontal("Parameters [Connected]", s_Styles.eventsHeader, new GUILayoutOption[0]);
            }
            GUILayout.FlexibleSpace();
            Rect rect = GUILayoutUtility.GetRect(s_Styles.addIcon, s_Styles.invisbleButton);
            if (EditorGUI.ButtonMouseDown(rect, s_Styles.addIcon, FocusType.Passive, s_Styles.invisbleButton))
            {
                GenericMenu menu = new GenericMenu();
                IEnumerator enumerator = Enum.GetValues(typeof(AnimatorControllerEventType)).GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        object current = enumerator.Current;
                        menu.AddItem(new GUIContent(current.ToString()), false, new GenericMenu.MenuFunction2(this.AddEventMenu), current);
                    }
                }
                finally
                {
                    IDisposable disposable = enumerator as IDisposable;
                    if (disposable == null)
                    {
                    }
                    disposable.Dispose();
                }
                menu.DropDown(rect);
            }
            GUILayout.EndHorizontal();
            GUILayout.BeginVertical(s_Styles.eventsBox, new GUILayoutOption[0]);
            this.m_EventScroll = EditorGUILayout.BeginScrollView(this.m_EventScroll, new GUILayoutOption[0]);
            string kFloatFieldFormatString = EditorGUI.kFloatFieldFormatString;
            EditorGUI.kFloatFieldFormatString = "f1";
            for (int i = 0; i < this.animatorController.GetEventCount(); i++)
            {
                string eventName = this.animatorController.GetEventName(i);
                AnimatorControllerEventType eventType = (AnimatorControllerEventType) this.animatorController.GetEventType(i);
                EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]);
                GUILayoutOption[] options = new GUILayoutOption[] { GUILayout.ExpandWidth(true) };
                eventName = EditorGUILayout.TextField(eventName, options);
                if (eventName != this.animatorController.GetEventName(i))
                {
                    Undo.RegisterUndo(this.animatorController, "Parameter renamed");
                    this.animatorController.SetEventName(i, MakeUniqueParameterName(eventName, this.animatorController));
                }
                EditorGUI.BeginDisabledGroup(this.liveLink && this.m_PreviewObject.IsParameterControlledByCurve(eventName));
                switch (eventType)
                {
                    case AnimatorControllerEventType.Vector:
                    {
                        EditorGUI.BeginChangeCheck();
                        Vector3 parameterVector = this.GetParameterVector(eventName);
                        float[] values = new float[] { parameterVector.x, parameterVector.y, parameterVector.z };
                        GUILayoutOption[] optionArray5 = new GUILayoutOption[] { GUILayout.MinWidth(92f) };
                        EditorGUI.MultiField(EditorGUILayout.GetControlRect(false, 16f, EditorStyles.numberField, optionArray5), s_Styles.vectorLabels, values, 0f);
                        if (EditorGUI.EndChangeCheck())
                        {
                            parameterVector.x = values[0];
                            parameterVector.y = values[1];
                            parameterVector.z = values[2];
                            this.SetParameterVector(eventName, parameterVector);
                        }
                        break;
                    }
                    case AnimatorControllerEventType.Float:
                    {
                        EditorGUI.BeginChangeCheck();
                        GUILayoutOption[] optionArray2 = new GUILayoutOption[] { GUILayout.Width(31f) };
                        float num2 = EditorGUILayout.FloatField(this.GetParameterFloat(eventName), optionArray2);
                        if (EditorGUI.EndChangeCheck())
                        {
                            this.SetParameterFloat(eventName, num2);
                        }
                        break;
                    }
                    case AnimatorControllerEventType.Int:
                    {
                        EditorGUI.BeginChangeCheck();
                        GUILayoutOption[] optionArray4 = new GUILayoutOption[] { GUILayout.Width(31f) };
                        int num3 = EditorGUILayout.IntField(this.GetParameterInt(eventName), optionArray4);
                        if (EditorGUI.EndChangeCheck())
                        {
                            this.SetParameterInt(eventName, num3);
                        }
                        break;
                    }
                    case AnimatorControllerEventType.Bool:
                    {
                        EditorGUI.BeginChangeCheck();
                        GUILayoutOption[] optionArray3 = new GUILayoutOption[] { GUILayout.Width(31f) };
                        bool flag = GUILayout.Toggle(this.GetParameterBool(eventName), string.Empty, optionArray3);
                        if (EditorGUI.EndChangeCheck())
                        {
                            this.SetParameterBool(eventName, flag);
                        }
                        break;
                    }
                }
                EditorGUI.EndDisabledGroup();
                EditorGUI.BeginDisabledGroup(this.liveLink);
                GUILayoutOption[] optionArray6 = new GUILayoutOption[] { GUILayout.Width(20f) };
                if (GUILayout.Button(s_Styles.removeIcon, s_Styles.invisbleButton, optionArray6))
                {
                    this.ResetTextFields();
                    Undo.RegisterUndo(this.animatorController, "Parameter removed");
                    this.animatorController.RemoveEvent(i);
                }
                EditorGUI.EndDisabledGroup();
                EditorGUILayout.EndHorizontal();
            }
            EditorGUI.kFloatFieldFormatString = kFloatFieldFormatString;
            EditorGUILayout.EndScrollView();
            GUILayout.EndVertical();
            GUILayout.EndArea();
        }

        private bool GetParameterBool(string eventName)
        {
            if (this.liveLink)
            {
                return this.m_PreviewObject.GetBool(eventName);
            }
            return this.animatorController.GetEventDefaultBool(this.animatorController.FindEvent(eventName));
        }

        private float GetParameterFloat(string eventName)
        {
            if (this.liveLink)
            {
                return this.m_PreviewObject.GetFloat(eventName);
            }
            return this.animatorController.GetEventDefaultFloat(this.animatorController.FindEvent(eventName));
        }

        private int GetParameterInt(string eventName)
        {
            if (this.liveLink)
            {
                return this.m_PreviewObject.GetInteger(eventName);
            }
            return this.animatorController.GetEventDefaultInt(this.animatorController.FindEvent(eventName));
        }

        private Vector3 GetParameterVector(string eventName)
        {
            if (this.liveLink)
            {
                return this.m_PreviewObject.GetVector(eventName);
            }
            return this.animatorController.GetEventDefaultVector(this.animatorController.FindEvent(eventName));
        }

        private StateMachine GetParentStateMachine()
        {
            if (this.m_BreadCrumbs.Count == 1)
            {
                return null;
            }
            return (this.m_BreadCrumbs[this.m_BreadCrumbs.Count - 2].target as StateMachine);
        }

        public void GoToBreadCrumbTarget(UnityEngine.Object target)
        {
            <GoToBreadCrumbTarget>c__AnonStorey4 storey = new <GoToBreadCrumbTarget>c__AnonStorey4 {
                target = target
            };
            int num = this.m_BreadCrumbs.FindIndex(new Predicate<BreadCrumbElement>(storey.<>m__0));
            while (this.m_BreadCrumbs.Count > (num + 1))
            {
                this.m_BreadCrumbs.RemoveAt(num + 1);
            }
            this.stateMachineGraphGUI.CenterGraph();
            this.blendTreeGraphGUI.CenterGraph();
        }

        private void GoToParentBreadcrumb()
        {
            if (this.m_BreadCrumbs.Count != 1)
            {
                this.m_BreadCrumbs.RemoveAt(this.m_BreadCrumbs.Count - 1);
                this.stateMachineGraphGUI.CenterGraph();
                this.blendTreeGraphGUI.CenterGraph();
            }
        }

        private void Init()
        {
            if (this.stateMachineGraph == null)
            {
                this.stateMachineGraph = ScriptableObject.CreateInstance<UnityEditor.Graphs.AnimationStateMachine.Graph>();
                this.stateMachineGraph.hideFlags = HideFlags.HideAndDontSave;
            }
            if (this.stateMachineGraphGUI == null)
            {
                this.stateMachineGraphGUI = this.stateMachineGraph.GetEditor() as UnityEditor.Graphs.AnimationStateMachine.GraphGUI;
            }
            if (this.blendTreeGraph == null)
            {
                this.blendTreeGraph = ScriptableObject.CreateInstance<UnityEditor.Graphs.AnimationBlendTree.Graph>();
                this.blendTreeGraph.hideFlags = HideFlags.HideAndDontSave;
            }
            if (this.blendTreeGraphGUI == null)
            {
                this.blendTreeGraphGUI = this.blendTreeGraph.GetEditor() as UnityEditor.Graphs.AnimationBlendTree.GraphGUI;
            }
            if (this.m_BreadCrumbs == null)
            {
                this.m_BreadCrumbs = new List<BreadCrumbElement>();
                this.ResetBreadCrumbs();
            }
            if (this.m_LayerExpansion == null)
            {
                this.m_LayerExpansion = new List<bool>();
            }
        }

        private void LayerView(EditorWindow host, Rect position)
        {
            GUILayout.BeginArea(position, s_Styles.overlayArea);
            this.m_LayerScroll = GUILayout.BeginScrollView(this.m_LayerScroll, new GUILayoutOption[0]);
            EditorGUIUtility.LookLikeControls(55f);
            int layerCount = this.animatorController.GetLayerCount();
            for (int i = 0; i < layerCount; i++)
            {
                if (this.BeginLayer(i))
                {
                    StateMachine layerStateMachine = this.animatorController.GetLayerStateMachine(i);
                    string layerName = this.animatorController.GetLayerName(i);
                    EditorGUI.BeginChangeCheck();
                    layerName = EditorGUILayout.TextField("Name", layerName, new GUILayoutOption[0]);
                    if (EditorGUI.EndChangeCheck() && !string.IsNullOrEmpty(layerName))
                    {
                        if (layerStateMachine != null)
                        {
                            ObjectNames.SetNameSmart(layerStateMachine, layerName);
                        }
                        Undo.RegisterUndo(this.animatorController, "Layer renamed");
                        this.animatorController.SetLayerName(i, layerName);
                    }
                    if (layerStateMachine == null)
                    {
                        layerStateMachine = new StateMachine {
                            hideFlags = HideFlags.HideInHierarchy
                        };
                        AssetDatabase.AddObjectToAsset(layerStateMachine, this.animatorController);
                        ObjectNames.SetNameSmart(layerStateMachine, this.animatorController.GetLayerName(i));
                        this.animatorController.SetLayerStateMachine(i, layerStateMachine);
                        this.ResetBreadCrumbs();
                    }
                    bool flag = InternalEditorUtility.HasPro();
                    if (i != 0)
                    {
                        if (this.liveLink)
                        {
                            this.m_PreviewObject.SetLayerWeight(i, EditorGUILayout.Slider("Weight", this.m_PreviewObject.GetLayerWeight(i), 0f, 1f, new GUILayoutOption[0]));
                        }
                        else
                        {
                            bool enabled = GUI.enabled;
                            GUI.enabled = false;
                            EditorGUILayout.Slider("Weight", 1f, 0f, 1f, new GUILayoutOption[0]);
                            GUI.enabled = enabled;
                        }
                        EditorGUILayout.LabelField("Masks", new GUILayoutOption[0]);
                        EditorGUI.indentLevel++;
                        this.animatorController.SetLayerHumanMask(i, EditorGUILayout.ObjectField("Human", this.animatorController.GetLayerHumanMask(i), typeof(AvatarBodyMask), false, new GUILayoutOption[0]) as AvatarBodyMask);
                        this.animatorController.SetLayerSkeletonMask(i, EditorGUILayout.ObjectField("Bones", this.animatorController.GetLayerSkeletonMask(i), typeof(AvatarSkeletonMask), false, new GUILayoutOption[0]) as AvatarSkeletonMask);
                        EditorGUI.indentLevel--;
                        this.animatorController.SetLayerBlendingMode(i, (AnimatorLayerBlendingMode) EditorGUILayout.EnumPopup("Blending", this.animatorController.GetLayerBlendingMode(i), new GUILayoutOption[0]));
                        if (flag)
                        {
                            if (EditorGUILayout.Toggle("Sync", this.animatorController.GetLayerSyncedIndex(i) > -1, new GUILayoutOption[0]))
                            {
                                int selectedIndex = 0;
                                List<string> list = new List<string>();
                                List<int> list2 = new List<int>();
                                for (int j = 0; j < layerCount; j++)
                                {
                                    if ((i != j) && (this.animatorController.GetLayerSyncedIndex(j) == -1))
                                    {
                                        list.Add(this.animatorController.GetLayerName(j));
                                        list2.Add(j);
                                        if (j == this.animatorController.GetLayerSyncedIndex(i))
                                        {
                                            selectedIndex = list.Count - 1;
                                        }
                                    }
                                }
                                int num5 = EditorGUILayout.Popup(string.Empty, selectedIndex, list.ToArray(), new GUILayoutOption[0]);
                                if (list2[num5] != this.animatorController.GetLayerSyncedIndex(i))
                                {
                                    this.animatorController.SetLayerSyncedIndex(i, list2[num5]);
                                    this.ResetBreadCrumbs();
                                }
                            }
                            else if (this.animatorController.GetLayerSyncedIndex(i) != -1)
                            {
                                this.animatorController.SetLayerSyncedIndex(i, -1);
                                this.ResetBreadCrumbs();
                            }
                        }
                    }
                    if (flag)
                    {
                        this.animatorController.SetLayerIKPass(i, EditorGUILayout.Toggle("IK Pass", this.animatorController.GetLayerIKPass(i), new GUILayoutOption[0]));
                    }
                }
                this.EndLayer();
            }
            GUILayout.EndScrollView();
            GUILayout.BeginHorizontal("Layers", s_Styles.layerHeader, new GUILayoutOption[0]);
            GUILayout.FlexibleSpace();
            if (GUILayout.Button(s_Styles.addIcon, s_Styles.invisbleButton, new GUILayoutOption[0]))
            {
                this.animatorController.AddLayer(MakeUniqueLayerName("New Layer", this.animatorController));
                this.m_SelectedLayerIndex = this.animatorController.GetLayerCount() - 1;
                StateMachine objectToAdd = new StateMachine {
                    hideFlags = HideFlags.HideInHierarchy
                };
                AssetDatabase.AddObjectToAsset(objectToAdd, AssetDatabase.GetAssetPath(this.animatorController));
                ObjectNames.SetNameSmart(objectToAdd, this.animatorController.GetLayerName(this.m_SelectedLayerIndex));
                this.animatorController.SetLayerStateMachine(this.m_SelectedLayerIndex, objectToAdd);
                this.ResetBreadCrumbs();
                this.m_LayerExpansion.Add(true);
            }
            GUILayout.EndHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.EndArea();
        }

        public static string MakeUniqueLayerName(string newName, AnimatorController controller)
        {
            int num2;
            string str = newName;
            int num = 0;
            do
            {
                num2 = 0;
                for (num2 = 0; num2 < controller.GetLayerCount(); num2++)
                {
                    if (str == controller.GetLayerName(num2))
                    {
                        str = newName + num.ToString();
                        num++;
                        break;
                    }
                }
            }
            while (num2 != controller.GetLayerCount());
            return str;
        }

        public static string MakeUniqueParameterName(string newName, AnimatorController controller)
        {
            int num2;
            string str = newName;
            int num = 0;
            do
            {
                num2 = 0;
                for (num2 = 0; num2 < controller.GetEventCount(); num2++)
                {
                    if (str == controller.GetEventName(num2))
                    {
                        str = newName + num.ToString();
                        num++;
                        break;
                    }
                }
            }
            while (num2 != controller.GetEventCount());
            return str;
        }

        private void NameView(Rect nameRect)
        {
            GUILayout.BeginArea(nameRect, s_Styles.overlayArea);
            GUILayout.BeginHorizontal(s_Styles.bottomBarDarkBg, new GUILayoutOption[0]);
            string str = "Assets/";
            string assetPath = AssetDatabase.GetAssetPath(this.animatorController);
            if (assetPath.StartsWith(str))
            {
                assetPath = assetPath.Remove(0, str.Length);
            }
            if (this.liveLink)
            {
                GUILayout.Label(this.previewObject.name, s_Styles.liveLinkLabel, new GUILayoutOption[0]);
            }
            GUILayout.Label(assetPath, s_Styles.nameLabel, new GUILayoutOption[0]);
            GUILayout.EndHorizontal();
            GUILayout.EndArea();
        }

        public void OnDisable()
        {
            BlendTreeInspector.blendTreeHierarchyChanged = (Action<BlendTree>) Delegate.Remove(BlendTreeInspector.blendTreeHierarchyChanged, new Action<BlendTree>(this.BlendTreeHierarchyChanged));
            StateTransitionsEditor.stateDirtyCallback = (System.Action) Delegate.Remove(StateTransitionsEditor.stateDirtyCallback, new System.Action(this.StateDirty));
        }

        public void OnEnable()
        {
            this.Init();
            this.DetectAnimatorControllerFromSelection();
            BlendTreeInspector.blendTreeHierarchyChanged = (Action<BlendTree>) Delegate.Combine(BlendTreeInspector.blendTreeHierarchyChanged, new Action<BlendTree>(this.BlendTreeHierarchyChanged));
            StateTransitionsEditor.stateDirtyCallback = (System.Action) Delegate.Combine(StateTransitionsEditor.stateDirtyCallback, new System.Action(this.StateDirty));
        }

        public void OnFocus()
        {
            this.DetectAnimatorControllerFromSelection();
            this.DetectPreviewObjectFromSelection();
        }

        public void OnGUI()
        {
            base.autoRepaintOnSceneChange = true;
            if (s_Styles == null)
            {
                s_Styles = new Styles();
            }
            BlendTreeInspector.currentController = this.m_AnimatorController;
            BlendTreeInspector.currentAnimator = this.m_PreviewObject;
            AnimatorController.lastActiveController = this.m_AnimatorController;
            AnimatorController.lastActiveLayerIndex = this.m_SelectedLayerIndex;
            this.DoToolbar(new Rect(0f, 0f, base.position.width, 17f));
            if (this.animatorController != null)
            {
                if (this.animatorController.isAssetBundled)
                {
                    Rect screenRect = new Rect(0f, 17f, base.position.width, base.position.height - 17f);
                    GUILayout.BeginArea(screenRect);
                    GUILayout.Label("Cannot show controller from asset bundle", new GUILayoutOption[0]);
                    GUILayout.EndArea();
                }
                else
                {
                    Rect position = new Rect(0f, 17f, base.position.width, base.position.height - 17f);
                    Rect layerView = new Rect(0f, 17f, 220f, this.PreCalcLayerViewHeight());
                    float height = this.PreCalcEventViewHeight();
                    Rect eventView = new Rect(0f, (base.position.height - height) - 17f, 220f, height);
                    Rect nameRect = new Rect(0f, base.position.height - 24f, base.position.width, 24f);
                    EventType type = Event.current.type;
                    if (ShouldCaptureEvent(eventView, layerView))
                    {
                        Event.current.type = EventType.Ignore;
                    }
                    BlendTreeInspector.parentBlendTree = null;
                    if (this.m_BreadCrumbs.Count > 0)
                    {
                        if (this.m_BreadCrumbs.Last<BreadCrumbElement>().target is StateMachine)
                        {
                            this.StateMachineView(position);
                        }
                        if (this.m_BreadCrumbs.Last<BreadCrumbElement>().target is BlendTree)
                        {
                            this.BlendTreeView(position);
                            BlendTreeInspector.parentBlendTree = this.m_BreadCrumbs.Last<BreadCrumbElement>().target as BlendTree;
                        }
                    }
                    if ((Event.current.type == EventType.MouseDown) && (Event.current.clickCount == 2))
                    {
                        this.GoToParentBreadcrumb();
                    }
                    if (Event.current.type != EventType.Used)
                    {
                        Event.current.type = type;
                    }
                    this.LayerView(this, layerView);
                    this.EventView(this, eventView);
                    this.NameView(nameRect);
                    if (Event.current.type == EventType.MouseDown)
                    {
                        GUIUtility.keyboardControl = 0;
                        EditorGUI.EndEditingActiveTextField();
                    }
                }
            }
        }

        public void OnProjectChange()
        {
            this.DetectAnimatorControllerFromSelection();
        }

        public void OnSelectionChange()
        {
            this.DetectAnimatorControllerFromSelection();
            this.DetectPreviewObjectFromSelection();
            base.Repaint();
        }

        private float PreCalcEventViewHeight()
        {
            float a = (this.animatorController.GetEventCount() * 20f) + 26f;
            return Mathf.Min(a, (base.position.height - 17f) * 0.5f);
        }

        private float PreCalcLayerViewHeight()
        {
            float a = 0f;
            for (int i = 0; i < this.animatorController.GetLayerCount(); i++)
            {
                if (this.m_LayerExpansion[i])
                {
                    if (i == 0)
                    {
                        a += 43f;
                    }
                    else
                    {
                        a += 81f;
                    }
                }
                else
                {
                    a += 23f;
                }
            }
            a += 30f;
            return Mathf.Min(a, (base.position.height - 17f) * 0.5f);
        }

        public void RebuildGraph()
        {
            this.stateMachineGraph.RebuildGraph();
            if (graphDirtyCallback != null)
            {
                graphDirtyCallback();
            }
        }

        private void ResetBreadCrumbs()
        {
            this.m_BreadCrumbs.Clear();
            if ((this.animatorController != null) && !this.animatorController.isAssetBundled)
            {
                StateMachine layerStateMachine = this.animatorController.GetLayerStateMachine(this.m_SelectedLayerIndex);
                if (layerStateMachine != null)
                {
                    this.stateMachineGraphGUI.ClearSelection();
                    this.AddBreadCrumb(layerStateMachine);
                    base.Repaint();
                }
            }
        }

        private void ResetTextFields()
        {
            EditorGUI.EndEditingActiveTextField();
            GUIUtility.keyboardControl = 0;
        }

        private void SetParameterBool(string eventName, bool value)
        {
            if (this.liveLink)
            {
                this.m_PreviewObject.SetBool(eventName, value);
            }
            else
            {
                Undo.RegisterUndo(this.animatorController, "Parameter default value changed");
                this.animatorController.SetEventDefaultBool(this.animatorController.FindEvent(eventName), value);
            }
        }

        private void SetParameterFloat(string eventName, float value)
        {
            if (this.liveLink)
            {
                this.m_PreviewObject.SetFloat(eventName, value);
            }
            else
            {
                Undo.RegisterUndo(this.animatorController, "Parameter default value changed");
                this.animatorController.SetEventDefaultFloat(this.animatorController.FindEvent(eventName), value);
            }
        }

        private void SetParameterInt(string eventName, int value)
        {
            if (this.liveLink)
            {
                this.m_PreviewObject.SetInteger(eventName, value);
            }
            else
            {
                Undo.RegisterUndo(this.animatorController, "Parameter default value changed");
                this.animatorController.SetEventDefaultInt(this.animatorController.FindEvent(eventName), value);
            }
        }

        private void SetParameterVector(string eventName, Vector3 value)
        {
            if (this.liveLink)
            {
                this.m_PreviewObject.SetVector(eventName, value);
            }
            else
            {
                Undo.RegisterUndo(this.animatorController, "Parameter default value changed");
                this.animatorController.SetEventDefaultVector(this.animatorController.FindEvent(eventName), value);
            }
        }

        private static bool ShouldCaptureEvent(Rect eventView, Rect layerView)
        {
            if (!layerView.Contains(Event.current.mousePosition) && !eventView.Contains(Event.current.mousePosition))
            {
                return false;
            }
            EventType type = Event.current.type;
            switch (type)
            {
                case EventType.MouseDown:
                case EventType.ScrollWheel:
                    return true;
            }
            return (EditorGUI.IsEditingTextField() && (type == EventType.KeyDown));
        }

        private void StateDirty()
        {
            this.RebuildGraph();
        }

        private void StateMachineView(Rect position)
        {
            this.stateMachineGraph.rootStateMachine = this.m_BreadCrumbs.First<BreadCrumbElement>().target as StateMachine;
            this.stateMachineGraph.parentStateMachine = this.GetParentStateMachine();
            this.stateMachineGraph.activeStateMachine = this.m_BreadCrumbs.Last<BreadCrumbElement>().target as StateMachine;
            this.stateMachineGraphGUI.BeginGraphGUI(this, position);
            this.stateMachineGraphGUI.OnGraphGUI();
            this.stateMachineGraphGUI.EndGraphGUI();
        }

        public AnimatorController animatorController
        {
            get
            {
                return this.m_AnimatorController;
            }
            set
            {
                this.m_AnimatorController = value;
                this.m_SelectedLayerIndex = 0;
                this.ResetBreadCrumbs();
                if ((this.m_PreviewObject != null) && (AnimatorController.GetAnimatorController(this.m_PreviewObject) != this.m_AnimatorController))
                {
                    this.m_PreviewObject = null;
                }
            }
        }

        public bool autoLiveLink
        {
            get
            {
                return this.m_AutoLiveLink;
            }
        }

        public bool liveLink
        {
            get
            {
                return (((EditorApplication.isPlaying && (this.m_PreviewObject != null)) && this.m_PreviewObject.enabled) && this.m_PreviewObject.gameObject.activeInHierarchy);
            }
        }

        public int motionSetIndex
        {
            get
            {
                return ((this.animatorController == null) ? 0 : this.animatorController.GetLayerMotionSetIndex(this.m_SelectedLayerIndex));
            }
        }

        public Animator previewObject
        {
            get
            {
                return this.m_PreviewObject;
            }
        }

        public int selectedLayerIndex
        {
            get
            {
                return this.m_SelectedLayerIndex;
            }
        }

        [CompilerGenerated]
        private sealed class <GoToBreadCrumbTarget>c__AnonStorey4
        {
            internal UnityEngine.Object target;

            internal bool <>m__0(AnimatorControllerTool.BreadCrumbElement o)
            {
                return (o.target == this.target);
            }
        }

        [Serializable]
        private class BreadCrumbElement
        {
            [SerializeField]
            private UnityEngine.Object m_Target;

            public BreadCrumbElement(UnityEngine.Object target)
            {
                this.m_Target = target;
            }

            public string name
            {
                get
                {
                    return ((this.m_Target == null) ? string.Empty : this.m_Target.name);
                }
            }

            public UnityEngine.Object target
            {
                get
                {
                    return this.m_Target;
                }
            }
        }

        private class Styles
        {
            public readonly GUIContent addIcon = EditorGUIUtility.IconContent("Toolbar Plus");
            public readonly GUIStyle bottomBarDarkBg = "In BigTitle";
            public readonly GUIStyle breadCrumbLeft = "GUIEditor.BreadcrumbLeft";
            public readonly GUIStyle breadCrumbMid = "GUIEditor.BreadcrumbMid";
            public readonly GUIStyle eventsBox = "flow overlay box";
            public readonly GUIStyle eventsHeader = "flow overlay header lower left";
            public readonly GUIStyle invisbleButton = "InvisibleButton";
            public readonly GUIStyle layerBox = "flow overlay box";
            public readonly GUIStyle layerFoldout = "flow overlay foldout";
            public readonly GUIStyle layerHeader = "flow overlay header upper left";
            public readonly GUIStyle liveLinkLabel = new GUIStyle("miniLabel");
            public readonly GUIStyle nameLabel = new GUIStyle("miniLabel");
            public readonly GUIStyle overlayArea = "flow overlay area left";
            public readonly GUIContent removeIcon = EditorGUIUtility.IconContent("Toolbar Minus");
            public readonly GUIContent[] vectorLabels = new GUIContent[] { new GUIContent(string.Empty), new GUIContent(string.Empty), new GUIContent(string.Empty) };

            public Styles()
            {
                this.nameLabel.alignment = TextAnchor.MiddleRight;
                this.nameLabel.padding = new RectOffset(0, 0, 0, 0);
                this.nameLabel.margin = new RectOffset(0, 0, 0, 0);
                this.liveLinkLabel.alignment = TextAnchor.MiddleLeft;
                this.liveLinkLabel.padding = new RectOffset(0, 0, 0, 0);
                this.liveLinkLabel.margin = new RectOffset(0, 0, 0, 0);
            }
        }
    }
}

